'use strict';

const Controller = require('egg').Controller;

class NspController extends Controller {
    async exist(id) {
        return await this.app.model.Live.findOne({
            where: {
                id
            }
        })

    }
    async checkToken(token) {
        const socket = this.ctx.socket;
        const id = socket.id;
        if (!token) {
            socket.emit(id, this.ctx.helper.parseMsg("error", "你没有权限访问该接口"))
            return false
        }
        let user = {};
        try {
            user = this.ctx.checkToken(token);
        } catch (error) {
            let fail = error.name === "TokenExpiredError"
                ? "token 已过期! 请重新获取令牌"
                : "Token 令牌不合法!";
            socket.emit(id, this.ctx.helper.parseMsg("error", fail))
            return false
        }
        let t = await this.ctx.service.cache.get("user_" + user.id)

        if (!t || t !== token) {
            socket.emit(id, this.ctx.helper.parseMsg(401, "Token1 令牌不合法!"))
            return false
        }
        user = await this.app.model.User.findByPk(user.id);


        if (!user) {
            socket.emit(id, this.ctx.helper.parseMag(400, "用户不存在或已被禁用"))
            return false

        }
        return user
    }
    async comment() {
        const nsp = this.app.io.of("/")
        const message = this.ctx.args[0] || {}
        const socket = this.ctx.socket;
        const id = socket.id;
        let { live_id, data, token } = message;
        if (!data) {
            socket.emit(id, this.ctx.helper.parseMsg('error', "请输入内容"))
            return
        }
        let user = await this.checkToken(token);
        if (!user) {
            return
        }
        let msg = await this.service.live.checkStatus(live_id);
        if (msg) {
            socket.emit(id, this.ctx.helper.parseMsg("error", msg))
            return
        }
        const room = "live_" + live_id;
        nsp.to(room).emit("comment", {
            user: {
                id: user.id,
                name: user.name ? user.name : user.username,
                avatar: user.avatar
            },
            id: this.ctx.randomString(20),
            content: data
        })
        this.app.model.Comment.create({
            content: data,
            live_id,
            user_id: user.id
        })
    }
    async gift() {
        const nsp = this.app.io.of("/")
        const message = this.ctx.args[0] || {}
        const socket = this.ctx.socket;
        const id = socket.id;
        let { live_id, gift_id, token } = message;
        // if (!data) {
        //     socket.emit(id, this.ctx.helper.parseMsg('error', "请输入内容"))
        //     return
        // }
        let user = await this.checkToken(token);
        if (!user) {
            return
        }
        let msg = await this.service.live.checkStatus(live_id);
        if (msg) {
            socket.emit(id, this.ctx.helper.parseMsg("error", msg))
            return
        }
        const room = "live_" + live_id;
        let giftt = await this.app.model.Gift.findOne({
            where: {
                id: gift_id
            }
        })
        let useee = await this.app.model.User.findOne({
            where: {
                id: user.id

            }
        })
        useee.coin = useee.coin - giftt.coin
        console.log()
        useee.save()
        console.log(giftt, "gifftt")
        nsp.to(room).emit("gift", {
            user: {
                id: user.id,
                name: user.name ? user.name : user.username,
                avatar: user.avatar
            },
            id: this.ctx.randomString(20),
            gift_id: gift_id,
            gift: giftt
        })
        this.app.model.LiveGift.create({
            gift_id: gift_id,
            live_id,
            user_id: user.id
        })
    }
    async leavelive() {
        const nsp = this.app.io.of("/")
        const message = this.ctx.args[0] || {}
        const socket = this.ctx.socket;
        const id = socket.id;
        let { live_id, token } = message;
        let user = await this.checkToken(token);
        if (!user) {
            return
        }
        let msg = await this.service.live.checkStatus(live_id);
        if (msg) {
            socket.emit(id, this.ctx.helper.parseMsg("error", msg))
            return
        }
        const room = "live_" + live_id;
        socket.leave(room)
        const rooms = [room]

        //更新在线用户列表
        nsp.adapter.clients(rooms, (err, clients) => {
            nsp.to(room).emit("online", {
                clients,
                action: "leave",
                user: {
                    id: user.id,
                    name: user.username,
                    avatar: user.avatar

                },

            })

        })
        let list = await this.service.cache.get("userList_" + room)
        if (list) {
            list = list.filter(item => item.id !== user.id)
            this.service.cache.set("userList_" + room, list)
        }
    }
    async joinlive() {
        const nsp = this.app.io.of("/")
        const message = this.ctx.args[0] || {}
        const socket = this.ctx.socket;
        const id = socket.id;
        let { live_id, token } = message;
        let user = await this.checkToken(token);
        if (!user) {
            return
        }
        let msg = await this.service.live.checkStatus(live_id);
        if (msg) {
            socket.emit(id, this.ctx.helper.parseMsg("error", msg))
            return
        }
        const room = "live_" + live_id;
        socket.join(room)
        const rooms = [room]
        let list = await this.service.cache.get("userList_" + room);
        list = list ? list : []
        list = list.filter(item => item.id !== user.id);
        list.unshift({
            id: user.id,
            name: user.username,
            avatar: user.avatar
        })
        this.service.cache.set("userList_" + room, list)
        //更新在线用户列表
        nsp.adapter.clients(rooms, (err, clients) => {
            nsp.to(room).emit("online", {
                clients,
                action: "join",
                user: {
                    id: user.id,
                    name: user.username,
                    avatar: user.avatar

                },
                data: list
            })

        })
        let liveUser = await this.app.model.LiveUser.findOne({
            where: {
                user_id: user.id,
                live_id
            }
        })
        if (!liveUser) {
            this.app.model.LiveUser.create({
                user_id: user.id,
                live_id
            })
            //总看人数+1
            let live = await this.exist(id);
            if (live) {
                live.increment({
                    look_count: 1
                })
            }
        }
    }
    async test() {
        console.log(this.ctx.args[0])

        let message = this.ctx.args[0]
        const socket = this.ctx.socket
        const id = this.ctx.socket.id;
        console.log(id, "id")
        socket.emit(id, id)
        console.log("-----------------")
    }
}

module.exports = NspController;
